package patrol.mobile.com.mobilepatrol.activity.security.emergency;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.CommonListActivity;
import patrol.mobile.com.mobilepatrol.activity.security.ConsTitles;
import patrol.mobile.com.mobilepatrol.activity.security.adapter.EmergencyCuringCheckAdapter;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.Curing1Bean;
import patrol.mobile.com.mobilepatrol.bean.CuringCheck3Bean;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.utils.CommonParamsHelper;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.TimeUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

public class EmergencyCuringCheck3Activity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener, EmergencyCuringCheckAdapter.IDataListaner {

    private EditText tv_worksUnit;
    private EditText tv_proWorks;
    private EditText tv_proPlan;
    private TextView tv_orgName;
    private TextView tv_inspector;
    private TextView tv_chackDate;

    private RecyclerView recyclerView;
    private TextView tvSave;

    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int limitSize = 4;
    private List<String> imgUUIDs = new ArrayList<>();
    private EmergencyCuringCheckAdapter emergencyCuringCheckAdapter;

    @BindView(R.id.listView)
    ListView listView;
    TextView tv_save;
    private int num;
    private String auditFlag = "";
    private String auditName = "";
    private String orgId = "";
    private String month = "";
    private String evalManager = "";
    private String unitEvaler = "";
    private String evaler = "";

    private String num1;
    private String chackPro = "";
    private String yes = "";
    private String resume = "";
    private String measure = "";
    private String situation = "";
    private String auditFlag1 = "";
    private String auditName1 = "";
    private List<String> imgOldUUIDs = new ArrayList<>();
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();
    private HashMap<String, Object> map1;
    private List<Map<String, String>> sendListMap = new ArrayList<>();

    @Override
    public void initTitle() {

        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(EmergencyCuringCheck3Activity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText(ConsTitles.EMERGENCY_CURING_CHECK_3);
    }

    @Override
    public void initData() {
        super.initData();
        View itemTopView = LayoutInflater.from(this).inflate(R.layout.activity_emergency_curing_check3_top, null);
        View itemFootView = LayoutInflater.from(this).inflate(R.layout.activity_emergency_curing_check3_bottom, null);

        recyclerView = itemFootView.findViewById(R.id.recyclerView);
        tvSave = itemFootView.findViewById(R.id.tv_save);
        listView.addHeaderView(itemTopView);
        listView.addFooterView(itemFootView);


        tv_worksUnit = itemTopView.findViewById(R.id.tv_worksUnit);
        tv_proWorks = itemTopView.findViewById(R.id.tv_proWorks);
        tv_proPlan = itemTopView.findViewById(R.id.tv_proPlan);
        tv_orgName = itemTopView.findViewById(R.id.tv_orgName);
        tv_inspector = itemTopView.findViewById(R.id.tv_inspector);
        tv_chackDate = itemTopView.findViewById(R.id.tv_chackDate);


        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

        requestData(getIntent().getStringExtra("id"));

    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_curing_check3;
    }

    @Override
    public void setListener() {

        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
    }


    private void requestData(String id) {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.EMERGENCY_CURING_3);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {

                CuringCheck3Bean curingCheck3Bean = GsonUtil.GsonToBean(response, CuringCheck3Bean.class);
                tv_worksUnit.setText(curingCheck3Bean.getWorksUnit());
                tv_proWorks.setText(curingCheck3Bean.getProWorks());
                tv_proPlan.setText(curingCheck3Bean.getProPlan());
                tv_orgName.setText(curingCheck3Bean.getOrgName());
                tv_inspector.setText(curingCheck3Bean.getInspector());
                tv_chackDate.setText(curingCheck3Bean.getChackDate());


                num = curingCheck3Bean.getNum();
                auditFlag = curingCheck3Bean.getAuditFlag();
                auditName = curingCheck3Bean.getAuditName();
                orgId = curingCheck3Bean.getOrgId();
                month = curingCheck3Bean.getMonth();
                evalManager = curingCheck3Bean.getEvalManager();
                unitEvaler = curingCheck3Bean.getUnitEvaler();
                evaler = curingCheck3Bean.getEvaler();


                List<CuringCheck3Bean.AbkSpecialExaminationItemListBean> abkSpecialExaminationItemListBeanList = curingCheck3Bean.getAbkSpecialExaminationItemList();
                emergencyCuringCheckAdapter = new EmergencyCuringCheckAdapter(EmergencyCuringCheck3Activity.this, abkSpecialExaminationItemListBeanList);
                listView.setAdapter(emergencyCuringCheckAdapter);
                emergencyCuringCheckAdapter.setDataListener(EmergencyCuringCheck3Activity.this);

                List<DeviceDetailImgBean> deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(EmergencyCuringCheck3Activity.this);

                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");

                    long currentTime = System.currentTimeMillis();
                    fileHelper.savePicture(currentTime + ".jpg", replace);
                    ImageItem imageItem = new ImageItem();
                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                    try {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                        imageItem.path = filePath;
//                        Glide.with(AdviceDetail2Activity.this).load(new File(filePath)).into(iv);
                        selImageList.add(imageItem);
                        imgOldUUIDs.add(deviceDetailImgBean.getId());
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        oldImgInfo.add(upImgInfoBean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });


            }
        });
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    ArrayList<ImageItem> images = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
            }
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(EmergencyCuringCheck3Activity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(EmergencyCuringCheck3Activity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }


    private void submit() {
        final HttpSender sender = new HttpSender(this, baseUrl, Urls.EMERGENCY_CURING_CHECK_3);
        HashMap<String, String> idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("worksUnit", tv_worksUnit.getText().toString());
        map1.put("orgName", tv_orgName.getText().toString());
        map1.put("orgId", orgId);
        map1.put("month", month);
        map1.put("chackDate", TimeUtils.timeString(System.currentTimeMillis()));
        map1.put("chackDate", TimeUtils.timeString(System.currentTimeMillis()));
        map1.put("proPlan", tv_proPlan.getText().toString());
        map1.put("inspector", tv_inspector.getText().toString());
        map1.put("evalManager", evalManager);
        map1.put("unitEvaler", unitEvaler);
        map1.put("evaler", evaler);
        map1.put("num", num);
        map1.put("auditFlag", TextUtils.isEmpty(auditFlag) ? "0" : "1");
        map1.put("auditName", auditName);


//        map1.put("chackPro", chackPro);
//        map1.put("yes", yes);
//        map1.put("resume", resume);
//        map1.put("measure", measure);
//        map1.put("situation", situation);

        sendListMap.clear();
        List<CuringCheck3Bean.AbkSpecialExaminationItemListBean> copyList = emergencyCuringCheckAdapter.getCopyList();
        for (int i = 0; i < copyList.size(); i++) {
            Map<String, String> map = new HashMap<>();
            map.put("num", copyList.get(i).getNum());
            map.put("chackPro", copyList.get(i).getChackPro());
            map.put("yes", copyList.get(i).getYes());
            map.put("resume", copyList.get(i).getResume());
            map.put("measure", copyList.get(i).getMeasure());
            map.put("situation", copyList.get(i).getSituation());
            map.put("auditFlag", TextUtils.isEmpty(copyList.get(i).getAuditFlag()) ? "0" : "1");
            map.put("auditName", copyList.get(i).getAuditName());
            sendListMap.add(map);
        }

        map1.put("abkSpecialExaminationItemList", sendListMap);

        map1.putAll(idDateBmnameMap);
        HashMap<String, String> map2 = new HashMap<>();
        map2.put("mainJson", GsonUtil.map2Json(map1));

        List<ImageItem> images = adapter.getImages();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
        for (int i = 0; i < images.size() - oldImgInfo.size(); i++) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("abkSpecialExamination");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        oldImgInfo.addAll(upImgInfoBeanList);
        map2.put("sysAttachmentsJson", GsonUtil.bean2Json(upImgInfoBeanList));
        sender.requestPost(map2, new HttpCallBack(sender) {

            @Override
            public void onError(String code, Call call, Exception e) {
                showToast("上传失败");
            }

            @Override
            public void onResponse(String code, String response) {
                showToast("上传成功");
                upImg();
            }
        });
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            List<ImageItem> images = adapter.getImages();
            for (ImageItem image : images) {
                File file = new File(image.path);
                list.add(file);
            }

            List<Map<String, String>> params = new ArrayList<>();
            for (UpImgInfoBean upImgInfoBean : oldImgInfo) {
                Map<String, String> map = new HashMap<>();
                map.put("id", upImgInfoBean.getId());
                map.put("type", "abkSpecialExamination");
                params.add(map);
            }

            LuBanHelper luBanHelper = new LuBanHelper(EmergencyCuringCheck3Activity.this, list, params);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("state") == 200) {
                            finish();
                            Toast.makeText(EmergencyCuringCheck3Activity.this, "上传图片成功！", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    public void doData(String num, String chackPro, String yes, String resume, String measure, String situation, String auditFlag, String auditName) {
//        this.num1 = num;
//        this.chackPro = chackPro;
//        this.yes = yes;
//        this.resume = resume;
//        this.measure = measure;
//        this.situation = situation;
//        this.auditFlag1 = auditFlag;
//        this.auditName1 = auditName;
    }


    @Override
    public void doList(List<CuringCheck3Bean.AbkSpecialExaminationItemListBean> copyList) {
//        copyList.clear();
//        for (int i = 0; i < copyList.size(); i++) {
//            Map<String, String> map = new HashMap<>();
//            map.put("num", copyList.get(i).getNum());
//            map.put("chackPro", copyList.get(i).getChackPro());
//            map.put("yes", copyList.get(i).getYes());
//            map.put("resume", copyList.get(i).getResume());
//            map.put("measure", copyList.get(i).getMeasure());
//            map.put("situation", copyList.get(i).getSituation());
//            map.put("auditFlag", TextUtils.isEmpty(copyList.get(i).getAuditFlag()) ? "0" : "1");
//            map.put("auditName", copyList.get(i).getAuditName());
//            sendListMap.add(map);
//        }

    }
}
